package quiz;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShowSelectedQuizServlet
 */
@WebServlet("/ShowSelectedQuiz")
public class ShowSelectedQuizServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowSelectedQuizServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		Quiz selectedQuiz = db.getQuiz(Integer.parseInt(request.getParameter("id")));
		
		request.setAttribute("selectedQuiz", selectedQuiz);
		
		/*
		 * This block of code returns the current user's results on this quiz. 
		 * a null value signifies no results on the quiz for this user
		 */

		ArrayList<Result> userRecentResults;
		Account currAcct = (Account) request.getSession().getAttribute("account");
		if (currAcct == null) userRecentResults = new ArrayList<Result>();
		else userRecentResults = db.getRecentResultsForQuizAndUser(selectedQuiz.getID(), currAcct.getID(), 8);
		request.setAttribute("userResultsOnQuiz", userRecentResults);
		
		/*
		 * This block of code returns results for this quiz.
		 */
		ArrayList<Result> topPerformingResults = db.getTopQuizResults(selectedQuiz, 8);
		request.setAttribute("topPerformers", topPerformingResults);
		
		ArrayList<Result> topPerformersInDay = db.getTopQuizResultsInDay(selectedQuiz.getID(), 8);
		request.setAttribute("topPerformersInDay", topPerformersInDay);
		
		ArrayList<Result> allRecentResults = db.getRecentResultsForQuiz(selectedQuiz.getID(), 8);
		request.setAttribute("allRecentResults", allRecentResults);
		
		Result avgResult = db.getAverageResultForQuiz(selectedQuiz.getID());
		request.setAttribute("summary", avgResult);
		
		RequestDispatcher dpatch = request.getRequestDispatcher("quiz.jsp");
		dpatch.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}

}
